<template>
    <!--已催回订单-->
    <div class="content_panel project_modules">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('collection.recalledList')}}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row>
                    <el-col :span="4">
                        <el-form-item prop="orderId" label="">
                            <el-input v-model="form.orderId" :placeholder="$t('common.innerOrderId')" clearable></el-input><!--内部订单号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="phone" label="">
                            <el-input v-model="form.phone" :placeholder="$t('common.mobileNumber')" clearable></el-input><!--手机号码-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userId" label="">
                            <el-input v-model="form.userId" placeholder="User ID" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="teamId" label="">
                            <el-select v-model="form.teamId" clearable :placeholder="$t('common.orderStatus')" style="width: 100%"><!--订单状态-->
                                <el-option v-for="item in collectStagesData" v-if="item.name !== 'S0'" :key="item.id" :value="item.id" :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="collectionUserName">
                            <select-account-list :type="selectDataType" v-model="form.collectionUserName" :placeholder="$t('common.recruiter')"></select-account-list>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="productChannel" label="">
                            <el-input v-model="form.productChannel" :placeholder="$t('common.applicationMarket')" clearable></el-input><!--应用市场-->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">
                        <el-form-item prop="source" label="">
                            <el-input v-model="form.source" :placeholder="$t('common.applyChannel')" clearable></el-input><!--申请渠道-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appVersion" label="">
                            <el-input v-model="form.appVersion" :placeholder="$t('common.versionName')" clearable></el-input><!--版本号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appPackage" label="">
                            <el-input v-model="form.appPackage" :placeholder="$t('system.appPackage')" clearable></el-input><!--app包名-->
                        </el-form-item>
                    </el-col>
                    <!--申请时间-->
                    <!-- <el-col :span="8">
                        <el-form-item prop="applyTime" label="">
                            <el-date-picker
                                    style="width:100%"
                                    v-model="form.applyTime"
                                    type="datetimerange"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="timestamp"
                                    :editable="false"
                                    range-separator="-"
                                    :default-time="['00:00:00', '23:59:59']"
                                    :start-placeholder="$t('common.applyStartTime')"
                                    :end-placeholder="$t('common.applyEndTime')"></el-date-picker>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <!--实际还款时间-->
                        <el-form-item prop="actRepayTime" style="width: 100%">
                            <el-date-picker
                                    :picker-options="pickerOptions"
                                    v-model="form.actRepayTime"
                                    type="datetimerange"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="timestamp"
                                    :editable="false"
                                    style="width: 100%;"
                                    range-separator="-"
                                    :default-time="['00:00:00', '23:59:59']"
                                    :start-placeholder="$t('common.actRepayStartTime')"
                                    :end-placeholder="$t('common.actRepayEndTime')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <!-- 伪名 -->
                    <el-col :span="4">
                        <el-form-item prop="whiteProductName" v-if="domain == 'Bene'"> <!---->
                            <el-input v-model="form.whiteProductName" :placeholder="$t('common.productName')" clearable><!----></el-input>
                        </el-form-item>
                        <el-form-item prop="kana" v-else> <!--姓名-->
                            <select-kana-list v-model="form.kana" :multiple="false" :placeholder="$t('finance.pseudonym')"></select-kana-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                        <el-button @click="exportData" type="primary">{{ $t('common.export') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->
        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <div class="totalAmount"><span>{{ $t('common.contractAmount') }}：PHP {{ contractAmount | formatCurrency }}</span><span>{{ $t('common.shouldRepayAmount') }}：PHP {{ shouldRepayAmount | formatCurrency }}</span><span>{{ $t('common.actRepayAmount') }}：PHP {{ actRepayAmount | formatCurrency }}</span></div>
                    <el-table ref="table" :data="tableData" @sort-change="changeTableSearch" style="width: 100%;"
                              :max-height="tableMaxHeight" :highlight-current-row="true">
                        <el-table-column prop="orderId" :label="$t('common.innerOrderId')" width="180"><!--内部订单号-->
                            <template slot-scope="{ row }">
                                <!-- <a @click="goDetail(row)" type="text" size="small" v-if="row.orderId" href="javascript:void(0);">{{ row.orderId }}</a> -->
                                <span>{{ row.orderId }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userId" label="User ID" min-width="120"></el-table-column>
                        
                        <el-table-column prop="userType" :label="$t('common.userType')" width="150"><!--用户类型-->
                            <template slot-scope="scope">
                                <span>{{ scope.row.userType | switchUserType }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userName" :label="$t('common.name')" min-width="160"></el-table-column><!--姓名-->
                        <!--手机号-->
                        <!-- <el-table-column prop="phone" :label="$t('common.mobileNumber')" min-width="120"></el-table-column> -->
                        <!--身份证号-->
                        <!-- <el-table-column prop="cardId" :label="$t('common.idCardNumber')" min-width="170"></el-table-column> -->
                        <el-table-column prop="loanTime" :label="$t('common.applyDate')" min-width="170"><!--申请日期-->
                            <template slot-scope="{ row }">{{ row.loanTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <el-table-column prop="periodDays" :label="$t('common.borrowingCycle')" min-width="100"><!--借款周期-->
                            <template slot-scope="{ row }">{{ row.periodDays != null ? row.periodDays : "--" }}</template>
                        </el-table-column>
                        <!-- <el-table-column prop="correctDay" :label="$t('common.rushingDays')" min-width="100">
                            <template slot-scope="{ row }">{{ row.correctDay != null ? row.correctDay : "--" }}</template>
                        </el-table-column> -->
                        <el-table-column prop="contractAmount" :label="$t('common.contractAmount')" width="100"><!--合同金额-->
                            <template slot-scope="{ row }">
                                <el-button v-if="domain=='Bene'" type="text" @click="showSpreadDialog(row)">{{ row.contractAmount | formatCurrency }}</el-button>
                                <div v-else>{{ row.contractAmount | formatCurrency }}</div>
                            </template>
                            <!-- <template slot-scope="{ row }" v-else></template> -->
                        </el-table-column>
                        <el-table-column prop="derateAmount" :label="$t('common.remitAmount')" width="150"><!--减免金额-->
                            <template slot-scope="{ row }">{{ row.derateAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column prop="lateRepay" :label="$t('common.shouldRepayAmount')" width="100"><!--应还金额-->
                            <template slot-scope="{ row }">{{ row.lateRepay | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column align="left" :label="$t('common.shouldRepayTime')" min-width="170" prop="repayTime"><!--应还时间-->
                            <template slot-scope="{ row }">
                                <el-button  v-if="domain=='Bene'" type="text" @click="showSpreadDialog(row)">{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</el-button>
                                <div v-else>{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</div>
                            </template>
                            <!-- <template slot-scope="{ row }" v-else>{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template> -->
                        </el-table-column>

                        <el-table-column prop="totalPeriods" v-if="showSpread" :label="$t('install.totalBorrowPeriod')" min-width="150"></el-table-column><!--借款总周期-->
                        <el-table-column prop="period" v-if="showSpread" :label="$t('install.currentBorrowPeriod')" min-width="150"></el-table-column><!--借款当前周期-->


                        <el-table-column prop="payedAmount" :label="$t('common.actRepayAmount')" width="150"><!--实还金额-->
                            <template slot-scope="{ row }">{{ row.payedAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column align="left" sortable="custom" :label="$t('common.actRepayTime')" min-width="170" prop="repayCompletionTime"><!--实际还款时间-->
                            <template slot-scope="{ row }">{{ row.repayCompletionTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <el-table-column prop="lateDays" sortable="custom" :label="$t('common.overdueDays')" min-width="140"><!--逾期天数-->
                            <template slot-scope="{ row }">
                                <div v-if="domain=='Bene'">
                                    <el-button type="text" @click="showSpreadDialog(row)">{{ row.lateDays != null ? row.lateDays : "--" }}</el-button>
                                </div>
                                <div v-else>{{ row.lateDays != null ? row.lateDays : "--" }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column sortable="custom" :label="$t('common.status')" min-width="100" prop="teamName"></el-table-column><!--状态-->
                        <el-table-column prop="collectionUserName" sortable="custom" :label="$t('common.recruiter')" min-width="110"></el-table-column><!--催收员-->
                        <el-table-column align="left" :label="$t('common.applicationMarket')" prop="productChannel" width="130"></el-table-column><!--应用市场-->
                        <el-table-column :label="$t('common.applyChannel')" prop="source" min-width="130"></el-table-column><!--申请渠道-->
                        <el-table-column :label="$t('system.appName')" prop="appName" min-width="130">
                            <template slot-scope="{ row }">{{ row.appName | switchAppName }}</template>
                        </el-table-column><!--APP名称-->
                        <el-table-column v-if="domain=='Bene'" :label="$t('finance.productName')" prop="whiteProductName" min-width="130"></el-table-column><!--伪名-->
                        <el-table-column v-else :label="$t('finance.pseudonym')" prop="kana" min-width="130">
                            <template slot-scope="{ row }">{{ row.kana | switchProductName }}</template>
                        </el-table-column><!--伪名-->
                        <el-table-column :label="$t('common.versionName')" prop="appVersion" min-width="130"></el-table-column><!--版本号-->
                        <el-table-column :label="$t('system.appPackage')" prop="appPackage" min-width="130"></el-table-column><!--APP包名-->
                        <!--<el-table-column prop="waitHour" :label="$t('common.processingTime')" min-width="100">&lt;!&ndash;处理时长&ndash;&gt;-->
                            <!--<template slot-scope="scope">-->
                                <!--<span class="noteRed" v-if="scope.row.waitHour >= 20">{{ scope.row.waitHour }}h</span>-->
                                <!--<span v-if="scope.row.waitHour && scope.row.waitHour < 20">{{ scope.row.waitHour }}h</span>-->
                            <!--</template>-->
                        <!--</el-table-column>-->
                    </el-table>
                    <!--分页组件-->
                    <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
                </div>
            </div>
        </div>
        <el-dialog :visible.sync = 'SpreadListObj.isVisible' width="70%">
            <spreadListDialog v-if="SpreadListObj.isVisible" :rowData="SpreadListObj.data"/>
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="()=>SpreadListObj.isVisible=false">{{$t('common.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import mixin from '@/service/mixin';
    import Pagination from '@/components/pagination';
    import SelectAppList from '@/components/select-app-list';
    import SelectAccountList from '@/components/select-account-list';
    import {domain} from '@/config/'
    import SelectKanaList from '@/components/select-kana-list';
    import spreadListDialog from '../../components/spread-list-Dialog'

    export default {
        name: 'collection-orderManage-rechargeList',
        components: {
            Pagination,
            SelectAppList,
            SelectAccountList,
            SelectKanaList,
            spreadListDialog
        },
        mixins: [mixin],
        data() {
            return {
                SpreadListObj:{
                    isVisible:false,
                    data:{},
                },
                domain:'',
                showSpread:false,
                user: this.$storage.get('user'),
                form: {
                    orderId: '',
                    phone: '',
                    userId: '',
                    applyTime: '',
                    orderState: '',
                    collectionUserName: '',
                    repayGradeOrder: '',
                    actRepayTime: [],
                    repayTimeOrder: '',
                    repayCompletionTimeOrder: '',
                    teamIdOrder: '',
                    collectionUserNameOrder: '',
                    productChannel: '',
                    source: '',
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                    appVersion: '',
                    appPackage: '',
                },
                rules: {
                    orderId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    phone: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    userId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    applyTime: [],
                    teamId: [],
                },
                shouldRepayAmount: 0,
                contractAmount: 0,
                actRepayAmount: 0,
                collectStagesData: [],
                selectDataType: {
                    systemType: 'recruiter',
                    roleCode: 127
                },
                roleCode: [],
                selectDate: ''
            };
        },
        computed: {
            hasPermission () {
                const list = ['127', '128', '140', '141']
                if (this.roleCode.length > 0 ) {
                    const bol = this.roleCode.every(item => list.findIndex(item1 => item1 === item) > -1)
                    return bol
                }
                return false
            },
            pickerOptions () {
                const data = {
                    onPick: ({ maxDate, minDate }) => {
                        console.log(maxDate, minDate)
                        this.selectDate = ''
                        let now = new Date()
                        now.setHours(23, 59, 59, 999)
                        // 催收员或催收组长
                        if (this.hasPermission) {
                            this.selectDate = now
                        }
                    },
                    disabledDate: time => {
                        if (this.selectDate) {
                            const date = this.selectDate
                            const minTime = new Date(date.setDate(date.getDate() - 20)).getTime()
                            const maxTime = new Date(date.setDate(date.getDate() + 20)).getTime()
                            return time.getTime() < minTime || time.getTime() > maxTime
                        } else {
                            return false
                        }
                    }
                }
                return data
            }
        },
        methods: {
            showSpreadDialog(row){
                this.SpreadListObj = {
                    isVisible:true,
                    data:row
                }
            },
            // 获取列表数据
            getTableData(page = this.page) {
                const params = this.fillParams(page);
                this.$api.collection.queryRepayDistributionTask(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                        this.getTotalAmount(params);
                    }
                    this.tableMaxHeight = document.body.clientHeight - 355;
                });
            },
            // 搜索列表数据
            search() {
                this.$refs.form.validate(val => {
                    if (val) {
                        this.page.currentPage = 1;
                        this.getTableData();
                    }
                });
            },
            // 导出列表数据
            exportData() {
                this.$refs.form.validate(val => {
                    if (val) {
                        const params = this.fillParams();
                        const user = this.$storage.get('user');
                        const language = this.$storage.getLocal('language');
                        params.language = language;
                        params.token = user.token;
                        params.source = encodeURIComponent(params.source); //针对特殊渠道转码
                        const {$apiConf} = this;
                        const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.collection.exportRepayOverdueInfoFie, ['page']);
                        this.$openNewBlank(url);
                    }
                });
            },
            // 配置查询和导出参数
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    collectionUserId: this.user.id,
                    orderId: form.orderId,
                    phone: form.phone,
                    teamId: form.teamId,
                    userId: form.userId,
                    lstartTime: '',
                    lendTime: '',
                    collectionUserName: form.collectionUserName,
                    productChannel: form.productChannel,
                    source: form.source,
                    appName: form.appName,
                    kana:form.kana,
                    whiteProductName:form.whiteProductName,
                    appVersion: form.appVersion,
                    appPackage: form.appPackage,
                    repayCompletionTimeStart: '',
                    repayCompletionTimeEnd: '',
                    queryType: 1,
                    queryFrom: 1,
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
//                Object.keys(form).forEach(key => {
//                    if (typeof form[key] === 'string' && form[key]) {
//                        form[key] = form[key].trim();
//                        params[key] = form[key];
//                    }
//                });
                if (form.applyTime) {
                    params.lstartTime = form.applyTime[0];
                    params.lendTime = form.applyTime[1];
                }
                console.log(form.actRepayTime)
                if(form.actRepayTime && form.actRepayTime.length >= 2) {
                    params.repayCompletionTimeStart = form.actRepayTime[0];
                    params.repayCompletionTimeEnd = form.actRepayTime[1];
                } else {
                    if (this.hasPermission) {
                        let date = new Date()
                        date.setHours(23, 59, 59, 999)
                        params.repayCompletionTimeStart = new Date(date.setDate(date.getDate() - 20)).getTime()
                        params.repayCompletionTimeEnd = new Date(date.setDate(date.getDate() + 20)).getTime()
                    }
                }
                if(form.repayGradeOrder) {
                    params.repayGradeOrder = form.repayGradeOrder;
                }
                if(form.repayTimeOrder) {
                    params.repayTimeOrder = form.repayTimeOrder;
                }
                if(form.repayCompletionTimeOrder) {
                    params.repayCompletionTimeOrder = form.repayCompletionTimeOrder;
                }
                if(form.teamIdOrder) {
                    params.teamIdOrder = form.teamIdOrder;
                }
                if(form.collectionUserNameOrder) {
                    params.collectionUserNameOrder = form.collectionUserNameOrder;
                }
                return params;
            },
            goDetail(row) {
                this.$openNewBlank(`#/conf/collection/order-manage/order-detail/${row.id}/${row.orderId}/${row.repayStatus}/${row.userId}/${row.repayScheduleId}/cs?appPackage=${row.appPackage}`);
            },
            changeTableSearch(val) {
                this.form.repayGradeOrder = '';
                this.form.repayTimeOrder = '';
                this.form.repayCompletionTimeOrder = '';
                this.form.teamIdOrder = '';
                this.form.collectionUserNameOrder = '';
                if(val.prop === 'lateDays') {
                    this.form.repayGradeOrder = (val.order === 'ascending') ? 'ASC' : 'DESC';
                }
                if(val.prop === 'repayTime') {
                    this.form.repayTimeOrder = (val.order === 'ascending') ? 'ASC' : 'DESC';
                }
                if(val.prop === 'repayCompletionTime') {
                    this.form.repayCompletionTimeOrder = (val.order === 'ascending') ? 'ASC' : 'DESC';
                }
                if(val.prop === 'teamName') {
                    this.form.teamIdOrder = (val.order === 'ascending') ? 'ASC' : 'DESC';
                }
                if(val.prop === 'collectionUserName') {
                    this.form.collectionUserNameOrder = (val.order === 'ascending') ? 'ASC' : 'DESC';
                }
                this.page.currentPage = 1;
                this.getTableData();
            },
            getTotalAmount(params) {
                params.repayStatus = 1;
                params.isOverdue = 1;
                params.isAssign = 1;
                this.$api.collection.queryHandlingOverdueTotal(params).then((res) => {
                    const {status, data, error} = res;
                    if (status === '1' && error === '00000000' && data) {
                        this.shouldRepayAmount = data.lateRepay;
                        this.contractAmount = data.contractAmount;
                        this.actRepayAmount = data.payedAmount;
                    }
                    else {
                        this.shouldRepayAmount = 0;
                        this.contractAmount = 0;
                        this.actRepayAmount = 0;
                    }
                });
            },
            getCollectStages() {
                const params = {
                    name: '',
                    active: 0
                };
                this.$api.collection.getCollectStages(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.collectStagesData = data;
                    }
                });
            },
            async getRoleCode () {
                const res = await this.$api.collection.queryCollectorRole()
                const { status, data } = res
                if (status === '1') this.roleCode = data || []
                console.log(this.roleCode)
                this.getTableData({currentPage: this.page.currentPage}, this.form);
            }
        },
        created() {
            this.domain = this.$storage.get('user').domain
            this.showSpread = domain.showSpread();
            this.getRoleCode()
            this.getCollectStages();
            this.form.repayCompletionTimeOrder = 'DESC';
        },
    };
</script>

<style lang="scss" scoped>
</style>
<style lang="scss">
    [data-page=collection-orderManage-rechargeList] {
        .noteRed {
            color: red;
        }
        .el-col {
            padding-left: 10px;
        }
        .el-table .cell, .el-table th > .cell {
            word-break: keep-all;
            word-wrap: break-word;
        }
        .el-tooltip__popper {
            max-width: 300px;
            word-break: break-all;
            background-color: #fff;
            box-shadow: 0px 0px 5px #ccc;
            color: #000;
        }
        .el-date-editor .el-range-separator {
            width: 35px;
        }
        .totalAmount {
            font-size:14px;
            font-weight:bold;
            margin:0 0 10px 0;
            span {
                margin: 0 50px 0 0;
            }
        }
    }
</style>
